# -*- coding: utf-8 -*-
import wave
from tencentcloud.common.common_client import CommonClient
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
import base64
from datetime import datetime
from https.UploadPaths import UploadPaths
import os
import uuid

SecretId = 'AKIDaTSQGD9GWsIveFnGj3GHNdmikdOgrpdU'
SecretKey = 'OqRtGXhijt0vmZXPCA0d8Rcguz796vcF'
endpoint = 'tts.tencentcloudapi.com'
try:
    cred = credential.Credential(SecretId, SecretKey)
    httpProfile = HttpProfile()
    httpProfile.endpoint = endpoint
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
except TencentCloudSDKException as err:
    print(f"实例化文字转语音失败,SecretId:{SecretId}>>>{err}")


def task_process(text, voice_type, emotion_category):
    try:

        # 构建请求参数
        params = {
            "Text": text,
            "SessionId": str(uuid.uuid4()),
            "VoiceType": voice_type,
            "EmotionCategory": emotion_category
        }
        common_client = CommonClient("tts", "2019-08-23", cred, "ap-guangzhou", profile=clientProfile)
        json_data = common_client.call_json("TextToVoice", params)
        audio = json_data['Response']['Audio']
        # 解码 Base64 数据
        audio_binary = base64.b64decode(audio)
        upload_paths = UploadPaths()
        upload_folder = upload_paths.get_path("temp")
        current_time = datetime.now().strftime("%Y%m%d%H%M%S")
        file_path = os.path.join(upload_folder, current_time + ".wav")
        path2 = f"../../{file_path}"
        # 创建 WAV 文件并写入解码后的音频数据
        with wave.open(path2, 'wb') as wavfile:
            # 设置 WAV 文件参数，这里参数根据你的实际情况可能需要调整
            wavfile.setnchannels(1)  # 单声道
            wavfile.setsampwidth(2)  # 采样宽度为2字节（16位）
            wavfile.setframerate(16000)  # 采样率为16000 Hz
            wavfile.writeframes(audio_binary)

        # 获取 WAV 文件时长
        duration = get_wav_duration(path2)
        print("文字转语音成功##############")
        return {"text": text, "file_path": file_path, "duration": duration}
    except TencentCloudSDKException as err:
        print(f"文字转语音失败,SecretId:{SecretId}>>>{err}")
    return None


def get_wav_duration(file_path):
    try:
        with wave.open(file_path, 'rb') as wavfile:
            # 获取采样率和采样点数量
            framerate = wavfile.getframerate()
            frames = wavfile.getnframes()

            # 计算时长（秒）
            duration = frames / float(framerate)

            print(f"WAV 文件时长：{duration} 秒")
            return duration
    except Exception as e:
        print(f"获取 WAV 文件时长失败：{e}")
        return None


if __name__ == '__main__':
    task_process("字节跳动语音合成", 301037, "neutral")
